package encaps.action;

import encaps.entities.Grant;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.resources.Labels;
import encaps.security.RoleManager;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class ViewUserAction extends Action {

    public static final String VIEW_USER = "viewUser";
    private ActionContext actionContext;

    public ViewUserAction(ActionContext context, Grant requiredGrant) {
        this.requiredGrant = requiredGrant;
        actionContext = context;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Long id = Long.parseLong(actionContext.getTextParameter(ID));
            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.findByPrimaryKey(id);
            String userLogin = user.getLogin();
            String header;
            Boolean edit = null;
            if (userLogin.equals(actionContext.getUserLogin())) {
                header = Labels.getLabel(Labels.YOUR_PROFILE);
                edit = false;
            } else {
                header = String.format(Labels.getLabel(Labels.VIEW_USER_MESSAGE_PATTERN), userLogin);
            }
            Element userElement = XMLHelper.toXMLElement(user, header, RoleManager.getRoleManager().getRole(actionContext.getUserRole()), edit);
            return userElement;
        } catch (FinderException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }
}
